/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.processing.split.mappers;

import aiaudio.processing.base.mapreduce.CoordinateDoubleValueKey;
import aiaudio.Application;
import aiaudio.database.tables.RatingsMatrixTable;
import aiaudio.database.tables.TemporaryTable;
import java.io.IOException;
import java.util.Map;
import java.util.NavigableMap;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;

/**
 *
 * @author nastya
 */
public class AddNecessaryUsersMapper extends TableMapper<ImmutableBytesWritable, CoordinateDoubleValueKey> {
    public static final String TEMPORAY_TABLE_WITH_NEEDED_USERS_NAME = "temporayTableWithNeededUsersName";

    HTable tableWithNeededUsers;
    
    @Override
    protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {
        NavigableMap<byte[], byte[]> familyMap = RatingsMatrixTable.getUsers(value);
        for (Map.Entry<byte[], byte[]> entry : familyMap.entrySet()) {
            byte[] user = entry.getKey();
            byte[] rating = entry.getValue();
            Get get = new Get(user);
            Result r = tableWithNeededUsers.get(get);
            long nd = TemporaryTable.getCountValue(r);
            
            if(nd >= 0){
                context.write(new ImmutableBytesWritable(key.get()), new CoordinateDoubleValueKey(Bytes.toDouble(rating), user));
                //TODO опасно!
                TemporaryTable.decrementCount(tableWithNeededUsers, user);
            }
        }
    }

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        super.setup(context);
        setupTemporaryTable(context);
    }

    private void setupTemporaryTable(Context context) {
        String tableName = context.getConfiguration().get(TEMPORAY_TABLE_WITH_NEEDED_USERS_NAME);
        tableWithNeededUsers = Application.database().getByName(tableName).getTable();
    }
    
}
